
import { ProColumns, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import {message, Modal, Select} from 'antd';
import React, {useEffect, useState} from 'react';
import {selectEmpIdAndNameUsingGet, updateClassByIdUsingPut} from "@/services/tlias-backend/classController";

interface Props {
  oldData?: API.Class;
  visible: boolean;
  columns: ProColumns<API.Class>[];  // 定义列数据
  onSubmit: (values: API.ClassEditDTO) => void;
  onCancel: () => void;
}

const handleUpdate = async (fields: API.ClassEditDTO) => {
  const hide = message.loading('正在更新');
  try {
    await updateClassByIdUsingPut(fields);
    hide();
    message.success('更新成功');
    return true;
  } catch (error: any) {
    hide();
    message.error('更新失败，' + error.message);
    return false;
  }
};

const UpdateModal: React.FC<Props> = (props) => {
  const { oldData, visible, columns, onSubmit, onCancel } = props;
  const [teacherList, setTeacherList] = useState<{ id: number; name: string }[]>([]);

  // 获取班主任数据
  useEffect(() => {
    if (visible) {
      selectEmpIdAndNameUsingGet().then((response) => {
        if (response.code === 200) {
          setTeacherList(response.data as any);  // 设置班主任列表
        } else {
          message.error('获取班主任列表失败');
        }
      });
    }
  }, [visible]);

  if (!oldData) {
    return <></>;
  }

  // 修改 columns，渲染班主任选择下拉框
  const updatedColumns = columns.map((column) => {
    if (column.dataIndex === 'empId') {  // 假设empId是班主任字段的dataIndex
      return {
        ...column,
        renderFormItem: (item: any, { type, defaultRender, ...rest }: any, form: any) => {
          if (type === 'form') {
            return (
              <Select
                placeholder="请选择班主任"
                options={teacherList.map(teacher => ({
                  label: teacher.name,
                  value: teacher.id,
                }))}
                defaultValue={oldData.empId}  // 设置默认选中班主任
                onChange={(value) => {
                  form.setFieldsValue({ empId: value });  // 设置empId字段
                }}
              />
            );
          }
          return defaultRender(item);
        }
      };
    }
    return column;
  });

  return (
    <Modal
      destroyOnClose
      title={'更新'}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <ProTable
        type="form"
        columns={updatedColumns}
        form={{
          initialValues: oldData,
        }}
        onSubmit={async (values: API.ClassEditDTO) => {
          const success = await handleUpdate({
            ...values,
            id: oldData.id as any,
          });
          if (success) {
            onSubmit?.(values);
          }
        }}
      />
    </Modal>
  );
};

export default UpdateModal;
